package com.danke.lib.pay;

import android.graphics.Bitmap;
import android.os.Build;
import android.text.TextUtils;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;

import org.json.JSONObject;

import androidx.annotation.RequiresApi;

/**
 * 招行一网通
 * APP支付文档 http://openhome.cmbchina.com/pay/AppPay/Download.aspx
 * H5支付文档  http://openhome.cmbchina.com/pay/H5Pay/APIList/OneCardPayAPI.aspx
 *
 * @author wupuquan
 * @version 1.0
 * @since 2019/1/9 11:21
 */
public class DKPayCmbWeb extends DKPayWeb {

    private static final String APP_ID = "0010630316";

    public DKPayCmbWeb(final DKPayActivity activity, JSONObject charge) {
        super(activity, charge);
    }

    @Override
    protected void init() {
        if (mWebView != null) {
            mWebView.setWebViewClient(new DKPayWebView.DKPayWebViewClient() {
                @Override
                public void onPageStarted(WebView view, String url, Bitmap favicon) {
                    super.onPageStarted(view, url, favicon);
                    DKPayLog.d("onPageStarted: " + url);
                }

                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    DKPayLog.d("shouldOverrideUrlLoading: " + url);
                    return super.shouldOverrideUrlLoading(view, url);
                }

                @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                    DKPayLog.d("shouldOverrideUrlLoading21: " + request.getUrl().toString());
                    return super.shouldOverrideUrlLoading(view, view.getUrl());
                }

                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
                    DKPayLog.d("onPageFinished: " + url);
                    // 成功 https://netpay.cmbchina.com/EUserPayOS/BaseHttp.dll?MB_EUserP_PayOK
                    if (url.contains("MB_EUserP_PayOK")) {
                        if (mActivity != null) {
                            mActivity.setResult(DKPayActivity.SUCCESS);
                        }
//                        if (mActivity != null) {
//                            AlertDialog dialog = new AlertDialog.Builder(mActivity)
//                                    .setTitle("支付成功")
//                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                                        @Override
//                                        public void onClick(DialogInterface dialog, int which) {
//                                            if (mActivity != null) {
//                                                mActivity.setResult(DKPayActivity.SUCCESS);
//                                            }
//                                        }
//                                    })
//                                    .create();
//                            dialog.setCancelable(false);
//                            dialog.setCanceledOnTouchOutside(false);
//                            dialog.show();
//                        }
                    }
                }

                @Override
                public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                    DKPayLog.d("onReceivedError: " + errorCode + ", " + description + ", " + failingUrl);
                    if (mActivity != null) {
                        mActivity.setResult(DKPayActivity.CANCEL);
                    }
                }
            });
        }
    }

    @SuppressWarnings("StringBufferMayBeStringBuilder")
    @Override
    protected void handleData(JSONObject credential) {
        try {
            String jsonRequestData = credential.optString("jsonRequestData");
            String channelUrl = credential.optString("ChannelUrl");
            String channelVersion = credential.optString("channelVersion");
            String requestData = "jsonRequestData=" + DKPayUtil.encodeUTF8(jsonRequestData);
            String h5Url = TextUtils.isEmpty(channelUrl) ? "https://netpay.cmbchina.com/netpayment/BaseHttp.dll?MB_EUserPay" : channelUrl;

            StringBuffer sb = new StringBuffer();
            String baseInfo = String.format("cmbpbsdk_version=%s&cmbpbsdk_appid=%s&cmbpbsdk_method=%s&sdk_deviceType=E&", channelVersion, APP_ID, "pay");
            sb.append(baseInfo);
            sb.append(requestData);
            load(h5Url, sb.toString().getBytes("UTF-8"));

            // 下面是App SDK的，暂时没啥用了
//            CMBRequest request = new CMBRequest();
//            request.mRequestData = requestData;
////                request.mRequestData = "charset=utf-8&jsonRequestData=" + encode(jsonRequestData);
////                request.mRequestData = "charset=utf-8&jsonRequestData=%7B%22version%22%3A%221.0%22%2C%22sign%22%3A%226AE3AC344AA5D9A75F154F27AC7FC72EBC447D9574453FA639FAC14493F9F060%22%2C%22signType%22%3A%22SHA-256%22%2C%22reqData%22%3A%7B%22agrNo%22%3A%22201707231234515%22%2C%22amount%22%3A%220.01%22%2C%22branchNo%22%3A%220755%22%2C%22cardType%22%3A%22%22%2C%22clientIP%22%3A%2299.6.150.83%22%2C%22date%22%3A%2220190119%22%2C%22dateTime%22%3A%2220190119221811%22%2C%22expireTimeSpan%22%3A%2230%22%2C%22extendInfo%22%3A%22FC77A8996853803BB6981F406BA84939CE96B8D57FFB20B653078B181FA9691D7CFF00D1D3EF21E6B338A3FD33490CAF12078BE885BB49F6016CF5A0314D21BF49738609F8386CB437A76A8DBE1E7E932DBDB18B7C69A8F10900FB8A3C98CB48833B5800A541DD6B5A12F65508C39CD1D51B32DD02CCE362BB5CE4D95E5D29921E603BBE3CA5B650652589013304CC2969E2A1046F91A1849B70001FE23EA8792560BE4FB7994D51BC7E7F5F5E08474F7090A44D435F2BFD7353B081DF80613817FD357CD472390A2EFEB1DA52D72DADD3BD5725FE42FA9D4B480F1804D6C9ADB7385C7CD1DCDF9F238A40DFF28BB3BB14%22%2C%22extendInfoEncrypType%22%3A%22RC4%22%2C%22lat%22%3A%2230.949505%22%2C%22lon%22%3A%2250.949506%22%2C%22merchantNo%22%3A%22000054%22%2C%22merchantSerialNo%22%3A%2220190119221811%22%2C%22mobile%22%3A%2213888888888%22%2C%22orderNo%22%3A%229999317045%22%2C%22payNoticePara%22%3A%22aaa%22%2C%22payNoticeUrl%22%3A%22https%3A%2F%2F99.6.150.226%3A44300%22%2C%22riskLevel%22%3A%223%22%2C%22signNoticePara%22%3A%22bb%22%2C%22signNoticeUrl%22%3A%22http%3A%2F%2F99.6.150.51%2F1.html%22%2C%22userID%22%3A%220000000001%22%2C%22subMerchantNo%22%3A%22%22%2C%22subMerchantName%22%3A%22%22%2C%22subMerchantTPCode%22%3A%22%22%2C%22subMerchantTPName%22%3A%22%22%2C%22payModeType%22%3A%22%22%7D%7D";
//            request.mCMBJumpUrl = ""; // 暂时先不调APP，先把H5调通
////                request.mCMBJumpUrl = "cmbmobilebank://CMBLS/FunctionJump?action=gofuncid&funcid=200013&serverid=CMBEUserPay&requesttype=post&cmb_app_trans_parms_start=here";
//            // APP支付 http://openhome.cmbchina.com/pay/AppPay/SDK/AndroidInterface.aspx
////                request.mH5Url = "https://netpay.cmbchina.com/netpayment/BaseHttp.dll?H5PayJsonSDK";
////                request.mH5Url = Constants.isDebug
////                        ? "http://121.15.180.66:801/netpayment/BaseHttp.dll?H5PayJsonSDK"
////                        : "https://netpay.cmbchina.com/netpayment/BaseHttp.dll?H5PayJsonSDK";
//            // H5支付 http://openhome.cmbchina.com/pay/H5Pay/APIList/OneCardPayAPI.aspx
//            request.mH5Url = h5Url;
////                request.mH5Url = Constants.isDebug
////                        ? "http://121.15.180.66:801/netpayment/BaseHttp.dll?MB_EUserPay"
////                        : "https://netpay.cmbchina.com/netpayment/BaseHttp.dll?MB_EUserPay";
//            request.mMethod = "pay";
////            mCMBApi.sendReq(request);
////                mCMBApi.sendReq(request, sCallback); // 这个带callback方法有问题，不要调
        } catch (Exception e) {
            e.printStackTrace();
            if (mActivity != null) {
                mActivity.setResult(DKPayActivity.FAIL, mActivity.getString(R.string.DKPay_fail));
            }
        }
    }

}
